import React, { useReducer, useContext } from 'react';

export const initialState = {
    wssb: true,
};

export const reducer = (state, action) => {
    switch (action.type) {
        case 'sb':
            return {
                ...state,
                wssb: !state.wssb,
            };
        default:
            return { ...state }
    }
};

export const createReducerContext = (reducer, initialState) => {
    // 在内部定义一个 StoreContext，用于传递 store
    const StoreContext = React.createContext(initialState);

    // Provider
    const ShareStateProvider = props => {
        const [store, dispatch] = useReducer(reducer, initialState);
        return (
            <StoreContext.Provider value={{ store, dispatch }}>
                {props.children}
            </StoreContext.Provider>
        );
    };

    // 用于取数据的自定义 Hook
    const useShareState = partialFn => {
        const { store, dispatch } = useContext(StoreContext);
        return {
            data: partialFn ? partialFn(store) : store,
            dispatch,
        };
    };

    return [ShareStateProvider, useShareState];
};

// 再组件外部创建 Provider 和
// export const [ShareStateProvider, useShareState] = createReducerContext(
//     reducer,
//     initialState
// );

